<?php
namespace Home\Controller;
use Think\Controller;
class PersonController extends CommonController{

	public function _initialize(){
		$this->getshopcart();
		$this->getcolmsg();
	}
	//默认显示用户个人中心界面
	public function index(){
		$this->isLogin();
		$this->loadordermsg();
		$this->loadcolmsg();
		$this->loadtime();
		$this->display("index");	
	}

	//载入日期
	public function loadtime(){
		$year =  date('Y');
		$month = date('m');
		$day = date('d');
		$xingqi = date('w');
		switch ($xingqi) {
			case '0':
				$xingqi = "星期日";
				break;
			case '1':
				$xingqi = "星期一";
				break;
			case '2':
				$xingqi = "星期二";
				break;
			case '3':
				$xingqi = "星期三";
				break;
			case '4':
				$xingqi = "星期四";
				break;
			case '5':
				$xingqi = "星期五";
				break;
			case '6':
				$xingqi = "星期六";
				break;
			
		}
		$this->assign("year",$year);
		$this->assign("month",$month);
		$this->assign("day",$day);
		$this->assign("xingqi",$xingqi);
	}

	//载入用户的个人订单数据
	public function loadordermsg(){
		$Order = M("Orderlist");
		$userid = $_SESSION['USERID'];
		//统计待发货的订单数量 Waiting for delivery 
		$wfdnum = $Order->where("userid = {$userid} AND status = 0 ")->count();
		//统计待收货的订单数量 Waiting for goods
		$wfgnum = $Order->where("userid = {$userid} AND status = 1")->count();
		//统计待评价的订单数量 Waiting for review
		$wfrnum = $Order->where("userid = {$userid} AND status = 2 ")->count();
		$this->assign("wfdnum",$wfdnum);
		$this->assign("wfgnum",$wfgnum);
		$this->assign("wfrnum",$wfrnum);
	}
	//载入用户收藏的商品信息
	public function loadcolmsg(){
		$Collection = M("Collection");
		$userid = $_SESSION['USERID'];
		$Goods = M("Goods");
		$collist=$Collection->where("userid = {$userid}")->select();
		if (!empty($collist)) {
			$colgoodslist = array();
			foreach ($collist as $value) {
				$goodsdata = $Goods->where("id ={$value['goodsid']}")->find();
				$value['goodsname']  = $goodsdata['goodsname'];
				$value['goodsorig'] = $goodsdata['goodsorig'];
				$value['goodsnow'] = $goodsdata['goodsnow'];
				$value['goodsimg']  = json_decode($goodsdata['goodsimg'],true);
				$colgoodslist[] = $value;
			}
			$this->assign("colgoodslist",$colgoodslist);
		}
	}
	//显示商城用户个人信息界面
	public function information(){
		$this->isLogin();
		$user_id=$_SESSION['USERID'];
		$User = M("User");
		$userdata = $User->where("id ={$user_id} ")->find();
		$userdata['headimg'] = json_decode($userdata['headimg'],true);
		$this->assign("userdata",$userdata);
		$this->display("information");
	}

	//用户保存个人信息
	public function saveInformation(){	
		$this->isLogin();
		$user_id = $_SESSION['USERID'];
		$User = M("User");
		$rules = array(
			array('username','require','用户名必须填写！'), // 用户名必须
			array('sex','require','性别必须填写！'), // 性别姓名必须
			array('telephone', '/^(0|86|17951)?(13[0-9]|15[012356789]|18[0-9]|14[57])[0-9]{8}$/', '手机号不合法！', 1, 'regex', 3), //验证手机号码是否合法
		);
		$data = $User->validate($rules)->create();
		if (!$data){
		// 如果创建失败 表示验证没有通过 输出错误提示信息
			$this->error($User->getError());
		}else{
			$headimg = I("post.imgs",'','');
			if (empty($headimg)) {
				$this->error("请上传个人头像");
			}
			$data['headimg'] = json_encode($headimg);
			$res=$User->where("id ={$user_id} ")->save($data);
			if (!$res) {
				$this->error("修改个人信息失败！");
			}else{
				$this->success("修改个人信息成功！");
			}
		}
			//$User->where("id ={$user_id} ")->save($data);

	}
	//显示安全设置界面
	public function safety(){
		$this->isLogin();
		$this->display("safety");
	}

	//显示修改密码界面
	public function password(){
		$this->isLogin();
		$this->display("password");
	}

	//保存修改后的密码
	public function savePwd(){
		$this->isLogin();
		$user_id = $_SESSION['USERID'];
		$User = M("User");
		$rules = array(
			array('password','require','密码必须填写！'), // 密码必须
			array('newpassword','require','新密码必须填写！'), // 新密码必须
			array('newpassword','8,16','密码长度为8-16位',0,'length'), // 验证新密码是否在指定长度范围
			array('newpassword','/^[A-Za-z0-9]+$/', '必须为英文字母或数字！',2),// 验证新密码格式是否正确
			array('repassword','newpassword','确认密码不一致',0,'confirm'), // 验证确认密码是否和密码一致	
		);
		$data=$User->validate($rules)->create();
		if (!$data) {
			// 如果创建失败 表示验证没有通过 输出错误提示信息
			$this->error($User->getError());
		}else{
			$password=I("post.password");
			$res=$User->where("id ={$user_id}  AND password='{$password}' ")->find();
			if (!$res) {
				$this->error("请输入正确的旧密码！");
			}else{
				$data['password'] = I("post.newpassword");
				$res=$User->where("id ={$user_id}")->save($data);
				if (!$res) {
					$this->error("修改个人账号密码失败！");
				}else{
					$this->success("修改个人账号密码成功！");
				}
			}
		}

	}

	//显示绑定电话号码界面
	public function bindphone(){
		$this->isLogin();
		$this->display("bindphone");
	}
	
	//保存新绑定的密码
	public function savePhone(){
		$this->isLogin();
		$user_id = $_SESSION['USERID'];
		$user_phone=$_SESSION['USERPHONE'];
		$User = M("User");
		$rules = array(
			array('newphone','require','手机号码必须填写！'), // 密码必须
			array('newphone', '/^(0|86|17951)?(13[0-9]|15[012356789]|18[0-9]|14[57])[0-9]{8}$/', '手机号不合法！', 1, 'regex', 3), //验证手机号码是否合法
		);
		$data = $User->validate($rules)->create();
		if (!$data) {
			$this->error($User->getError());
		}else{
			$newphone = I("post.newphone");
			$map['id']  = array('not in',$user_id);
			$map['telephone'] = array('eq',$newphone);
			$res=$User->where($map)->find();
			if (!$res){
				$data['telephone'] = $newphone;
				$res=$User->where("id ={$user_id}")->save($data);
				if (!$res) {
					$this->error("绑定新的手机号码失败！");
				}else{
					$_SESSION['USERPHONE'] = $newphone;
					$this->success("绑定新的手机号码成功！");
				}
			}else{
				$this->error("手机号码已被占用！");
			}
		}
	}

	//显示绑定邮箱界面
	public function email(){
		$this->isLogin();
		$this->display("email");
	}

	//保存新的绑定邮箱
	public function saveemail(){
		$this->isLogin();
		$user_id = $_SESSION['USERID'];
		$user_email=$_SESSION['USEREMAIL'];
		$User = M("User");
		$rules = array(
			array('newemail','require','邮箱必须填写！'), // 邮箱必须
		);
		$data = $User->validate($rules)->create();
		if (!$data) {
			$this->error($User->getError());
		}else{
			$newemail = I("post.newemail");
			$map['id']  = array('not in',$user_id);
			$map['email'] = array('eq',$newemail);
			$res=$User->where($map)->find();
			if (!$res){
				$data['email'] = $newemail;
				$res=$User->where("id ={$user_id}")->save($data);
				if (!$res) {
					$this->error("绑定新的邮箱失败！");
				}else{
					$_SESSION['USEREMAIL'] = $newemail;
					$this->success("绑定新的邮箱成功！");
				}
			}else{
				$this->error("邮箱已被占用！");
			}
		}
	}

	//显示地址管理界面
	public function address(){
		$this->isLogin();
		//获取省份
		$Province = M("Province");
		$provincelist=$Province->order("id asc")->select();
		//获取用户地址
		$user_id = $_SESSION['USERID'];
		$Address = M('Useraddress');
		$Addressdata = $Address->where("userid ={$user_id}")->select();
		if (!empty($Addressdata)) {
			$City = M("City");
			$District = M('District');
			$useraddlist = array();
			foreach ($Addressdata as $value) {
				$value['province'] = $Province->where("id ={$value['province']}")->getField("provincename");
				$value['city'] = $City->where("id = {$value['city']}")->getField("cityname");
				$value['district'] = $District->where("id ={$value['district']}")->getField("districtname");
				$useraddlist[ ] =$value;
			}
			$this->assign("useraddresslist",$useraddlist);
		}
		
		$this->assign("provincelist",$provincelist);
		$this->display("address");
	}
	//添加新地址  或者编辑原有地址
	public function addaddress(){
		$this->isLogin();
		$Address = M('Useraddress');
		$rules = array(
			array('consignor','require','收货人必须填写！'), // 收货人必须
			array('telephone','require','电话号码必须填写！'), // 电话号码必须
			array('telephone', '/^(0|86|17951)?(13[0-9]|15[012356789]|18[0-9]|14[57])[0-9]{8}$/', '手机号不合法！', 1, 'regex', 3), //验证手机号码是否合法
			array('province', '/^[1-9]\d*$/', '请选择省份！', 1, 'regex', 3), //验证是否选择省份
 			array('city', '/^[1-9]\d*$/', '请选择城市！', 1, 'regex', 3), //验证是否选择城市
 			array('district', '/^[1-9]\d*$/', '请选择县区！', 1, 'regex', 3), //验证是否选择县区
 			array('detaddress','require','详细地址必须填写！'), // 详细地址必须
		);

		$data = $Address->validate($rules)->create();
		if (!$data){
			$this->error($Address->getError());
		}else{
			$data['detaddress'] = I("post.detaddress",'','');
			$data['userid'] = $_SESSION['USERID'];
			$data['addtime'] = time();
			$addressid=I("get.addressid");
			//判断是否添加或者修改地址
			if (!empty($addressid)) {
				$res = $Address->where("id={$addressid}")->save($data);
				if (!$res){
					$this->error("修改地址失败！");
				}else{
					$this->success("修改地址成功！");
				}
			}else{
				$res = $Address->add($data);
				if (!$res){
					$this->error("添加新地址失败！");
				}else{
					$this->success("添加新地址成功！");
				}
			}
			
			
		}
	}

	//显示编辑地址界面
	public function editaddress(){
		$this->isLogin();
		$addressid = I("get.addressid");
		$Address = M('Useraddress');
		$addressdata=$Address->where("id ={$addressid}")->find();
		if (!empty($addressdata)) {
			$Province = M("Province");
			$City = M('City');
			$District = M('District');
			$provincelist = $Province->order("id asc")->select();
			$citylist = $City->where("provinceid ={$addressdata['province']}")->order("id asc")->select();
			$districtlist =  $District->where("cityid ={$addressdata['city']} ")->order("id asc")->select();
			$addressdata['provincename'] = $Province->where("id ={$addressdata['province']}")->getField("provincename");
			$addressdata['cityname'] = $City->where("id = {$addressdata['city']}")->getField("cityname");
			$addressdata['districtname'] = $District->where("id ={$addressdata['district']}")->getField("districtname");
			$this->assign("addressdata",$addressdata);
			$this->assign("provincelist",$provincelist);
			$this->assign("citylist",$citylist);
			$this->assign("districtlist",$districtlist);
		}
		$this->display("editaddress");
	}
	//显示订单管理界面
	public function order(){
		$this->isLogin();
		$Order = M('Orderlist');
		$Goods = M("Goods");
		$User = M('User');
		//分页输出全部订单
		$userid = $_SESSION['USERID'];
		$map['status'] = array('neq',3);
		$map['userid'] = array('eq',$userid);
		$count = $Order->where($map)->count();
		
		$Page    = new \Think\Page($count,3);// 实例化分页类 传入总记录数和每页显示的记录数(3)
		$Page->setConfig('header',"<span>共<b>%TOTAL_ROW%</b>条记录 第<b>%NOW_PAGE%</b>页/共<b>%TOTAL_PAGE%</b>页</span>");
		$Page->setConfig('first','首页');
		$Page->setConfig('last','共%TOTAL_PAGE%页');
		$Page->setConfig('prev','<<');
		$Page->setConfig('next','>>');
		$Page->setConfig('theme',"%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%");
		$show  = $Page->show();// 分页显示输出
		// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
		$list = $Order->order('id asc')->where($map)->limit($Page->firstRow.','.$Page->listRows)->select();
		$Orderdatalist = array();
		foreach ($list as $value) {
			$value['goodslist'] = json_decode($value['goodslist'],true);
			$value['username'] = $User->where("id ={$value['userid']}")->getField("username");
			//取出商品信息
			foreach ($value['goodslist'] as $key => $val) {
				$buygoods=$Goods->where("id ={$val[0]}")->find();
				$buygoods['number'] = $val[1];
				$buygoods['goodsimg'] = json_decode($buygoods['goodsimg'],true);
				$value['goodslist'][$key] = $buygoods;
			}
			$Orderdatalist[ ] = $value;
		}
		$this->Fstatus();
		$this->assign("orderdatalist",$Orderdatalist);
		$this->assign("show",$show);
		$this->display("order");

	}

	public function Fstatus(){
		$Order = M('Orderlist');
		$Goods = M("Goods");
		$User = M('User');
		$userid = $_SESSION['USERID'];
		$list = $Order->order('id asc')->where("userid ={$userid}")->select();
		$Orderdatalist = array();
		foreach ($list as $value) {
			$value['goodslist'] = json_decode($value['goodslist'],true);
			$value['username'] = $User->where("id ={$value['userid']}")->getField("username");
			//取出商品信息
			foreach ($value['goodslist'] as $key => $val) {
				$buygoods=$Goods->where("id ={$val[0]}")->find();
				$buygoods['number'] = $val[1];
				$buygoods['goodsimg'] = json_decode($buygoods['goodsimg'],true);
				$value['goodslist'][$key] = $buygoods;
			}
			$Orderdatalist[ ] = $value;
		}
		$this->assign("orderlist",$Orderdatalist);
	}
	//显示商品收藏页面
	public function collection(){
		$this->isLogin();
		$this->loadcolmsg();
		$this->display("collection");

	}
	//显示评价页面
	public function comment(){
		$this->isLogin();
		$this->loadcotmsg();
		$this->display("comment");
	}

	//载入评价信息
	public function loadcotmsg(){
		$userid = $_SESSION['USERID'];
		$Review = M("Review");
		$cotmsg = $Review->where("userid ={$userid}")->select();
		if (!empty($cotmsg)) {
			$cotlist = array();
			$Goods = M("Goods");
			foreach ($cotmsg as  $value) {
				$goodsdata=$Goods->where("id ={$value['goodsid']}")->find();
				$value['goodsimg'] = json_decode($goodsdata['goodsimg'],true);
				$value['goodsname'] = $goodsdata['goodsname'];
				$cotlist[] = $value;
			}
			$this->assign("cotlist",$cotlist);
		}
	}
	//显示用户足迹页面
	public function foot(){
		$this->loadfootmsg();
		$this->display("foot");
	}

	//载入用户足迹信息（商品浏览记录）
	public function loadfootmsg(){
		$userid = $_SESSION['USERID'];
		$Foot = M("Foot");
		$footmsg = $Foot->where("userid ={$userid}")->order("foottime desc")->select();
		if (!empty($footmsg)) {
			$Goods = M("Goods");
			$footlist = array();
			foreach ($footmsg as $key => $value) {
				$goodsdata = $Goods->where("id = {$value['goodsid']}")->find();
				$value['goodsname'] = $goodsdata['goodsname'];
				$value['goodsimg'] = json_decode($goodsdata['goodsimg'],true);
				$value['goodsorig'] = $goodsdata['goodsorig'];
				$value['goodsnow'] = $goodsdata['goodsnow'];
				$footlist[] = $value;
			}
			$this->assign("footlist",$footlist);
		}
	}
}